const path = require("path");
const axios = require("axios");
const fs = require("fs-extra");
const chalk = require("chalk");
const { API_DOC_URL } = require("./config");
const OPEN_API_LOCAL_PATH = path.resolve(__dirname, "./.local/open-api.json");

async function getApiDoc(url) {
  const apiUrl = `${url || API_DOC_URL}/v2/api-docs`;
  console.log(chalk.redBright(`api url: ${apiUrl}`));
  const res = await axios.get(apiUrl);
  try {
    fs.writeJSONSync(OPEN_API_LOCAL_PATH, res.data, { spaces: 2 });
  } catch (e) {
    //no-op
  }
  return res.data;
}

async function getLocalApiDoc() {
  return fs.readJSONSync(OPEN_API_LOCAL_PATH, { throws: false });
}

async function getApi(url) {
  return getApiDoc(url);
  // return getLocalApiDoc();
}

module.exports = {
  getApi,
};
